# encoding=utf-8
'''
Created on 2012-12-30

@author: Administrator
'''
from base.common import createBaseHtml, retSuccess
from base.dbCommon import getPage, getLimit, convertToArray
from config.db.models import moduleTable, Component
from config.settings import PROJECT_PATH



formJson = [
          {'id':'id', 'key':'Hidden', 'name':'主键'},
          {'id':'name', 'key':'Input', 'name':'组件名称', 'noNull':True},
          {'id':'jsonKey', 'key':'Input', 'name':'键值', 'noNull':True},
          {'id':'remark', 'key':'TextArea', 'name':'功能简述'},
          {'id':'content', 'key':'TextArea', 'name':'内容'},
          {'key':'Submit', 'action':'component.create','relaTable':'templateTable','back':'closeTab'},
         ]

filePath=PROJECT_PATH+"/yqy/html/templates/component/"

def getOneById(modid):
    retBean = Component.objects.filter(id=modid)
    return convertToArray(retBean.values())[0]    


class component():
    
    def add(self):
        return createBaseHtml(formJson)
     
    def create(self):
        
        item = Component()
        for temp in self.request.params:
            item.setAttr(temp, self.request.params.get(temp))
        item.save()
        fileName=item.jsonKey+".html"
        path=filePath+fileName
        uploadFile=open(path,"wb")
        uploadFile.write(item.content)
        uploadFile.close()
        return getOneById(item.id)
        
    def query(self):
        qryName = self.request.GET.get("name")
        page = getPage(self.request)
        limit = getLimit(page)
        retBean = None
        if qryName:
            retBean = Component.objects.filter(name__icontains=qryName)
        else:
            retBean = Component.objects.all()
        retBean = retBean[limit.get("start"):limit.get("end")]
        
        return convertToArray(retBean.values())    
    def gotoEdit(self):
        
        modId = self.request.POST.get("id")
        
        return getOneById(modId) 
    
    def delRow(self):
        modId = self.request.POST.get("id")
        moduleTable.objects.get(id=modId).delete()
        return retSuccess("删除成功")
        
    
